package com.imonsoft.sqm.service.excel.QuanlitySystemExcel;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.imonsoft.common.constant.ConstantDict;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.common.util.PDFUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.pojo.business.supplier_quality.QualitySystem;
import com.imonsoft.sqm.service.basedata.DictionaryService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import com.imonsoft.sqm.service.business.supplier_quality.QualitySystemService;
import com.imonsoft.sqm.service.excel.BaseExcel.ExcelService;

@Service("quanlitySystemExcelService")
public class QuanlitySystemExcelServiceImpl implements
		QuanlitySystemExcelService {
	@Autowired
	private QualitySystemService qualitySystemService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private ExcelService excelService;

	/**
	 * 通过模板写出ECCEL
	 * 
	 * @param request
	 * @param ids
	 * @param response
	 */
	@Override
	public void txExportExcel(HttpServletRequest request, String ids,
			HttpServletResponse response) {
		createExcel(request, ids, response);
		excelService.loadExcelModel(request, response,
				ConstantSqm.EXCEL_QUALITY_SYSTEM_OUT);
	}
	public void deleteExcelAndPdf(HttpServletRequest request) {
		// 删除如果之前未删除，则删除pdf
		File everFilePdf = new File(request.getSession().getServletContext()
				.getRealPath("/excelModel/")
				+ "/" + ConstantSqm.PDF_QUALITY_SYSTEM_OUT);
		if (everFilePdf.exists()) {
			everFilePdf.delete();
		}
	}
	/**
	 * 为邮件生成PDF
	 */
	@Override
	public void txExportPdf(HttpServletRequest request, String id,
			HttpServletResponse response) {
		deleteExcelAndPdf(request);
			createExcel(request, id, response);
			convertExcelToPdf(
					request.getSession().getServletContext()
							.getRealPath("/excelModel/")
							+ "/" + ConstantSqm.EXCEL_QUALITY_SYSTEM_OUT,
					request.getSession().getServletContext()
							.getRealPath("/excelModel/")
							+ "/" + ConstantSqm.PDF_QUALITY_SYSTEM_OUT);
			
	}

	public void convertExcelToPdf(String filePath, String outFile) {
		PDFUtil pu = new PDFUtil();
		pu.excelToPDF(filePath, outFile);
	}

	@Override
	public List<QualitySystem> getQualitySystemList(String ids) {
		List<QualitySystem> qualitySystemList = new ArrayList<QualitySystem>();
		if (ids != null && StringUtil.isNotEmpty(ids)) {
			String[] getId = ids.split(",");
			for (int i = 0; i < getId.length; i++) {
				QualitySystem qualitySystem = qualitySystemService.get(Long
						.parseLong(StringUtil.fixup(getId[i])));
				if (qualitySystem != null
						&& qualitySystem.getState().equals(
								ConstantSqm.STATUS_NORMAL)) {
					qualitySystemList.add(qualitySystem);
				}
			}
		} else {
			List<QualitySystem> qualitySystemAllList = qualitySystemService
					.queryAll();
			if (qualitySystemAllList != null && qualitySystemAllList.size() > 0) {
				for (int i = 0; i < qualitySystemAllList.size(); i++) {
					QualitySystem qualitySystem = qualitySystemAllList.get(i);
					if (qualitySystem != null
							&& qualitySystem.getState().equals(
									ConstantSqm.STATUS_NORMAL)) {
						qualitySystemList.add(qualitySystem);
					}
				}
			}
		}
		return qualitySystemList;
	}

	public void createExcel(HttpServletRequest request, String ids,
			HttpServletResponse response) {
		String errorMsg = "";
		try {
			File tFile = new File(request.getSession().getServletContext()
					.getRealPath("/excelModel/")
					+ "/" + ConstantSqm.EXCEL_QUALITY_SYSTEM);// 创建模板文件对象
			File outFile = new File(request.getSession().getServletContext()
					.getRealPath("/excelModel/")
					+ "/" + ConstantSqm.EXCEL_QUALITY_SYSTEM_OUT);// 创建输出文件对象
			// 创建文件输出流对象
			FileOutputStream os = new FileOutputStream(outFile);
			// 模板工作簿对象
			Workbook tBook = Workbook.getWorkbook(tFile);
			// 输出工作簿对象
			WritableWorkbook wbook = Workbook.createWorkbook(os, tBook);
			WritableSheet sheet = wbook.getSheet(0);
			sheet.setName("质量体系");
			WritableCellFormat cellFormat = new WritableCellFormat();
			cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
			// 设置对齐方式
			cellFormat
					.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
			cellFormat.setAlignment(jxl.format.Alignment.LEFT);
			// 设置字体
			WritableFont bodyFont = new WritableFont(WritableFont.ARIAL, 12);
			cellFormat.setFont(bodyFont);
			// 第x列，第y行
			List<QualitySystem> qualitySystemList = getQualitySystemList(ids);
			if (qualitySystemList != null && qualitySystemList.size() > 0) {
				QualitySystem qualitySystem = qualitySystemList.get(0);
				// 供应商数据
				String linkMan = "";
				if (qualitySystem.getSupplierId() != null) {
					Supplier supplier = supplierService.get(Long
							.parseLong(StringUtil.fixup(qualitySystem
									.getSupplierId())));
					Label label_reason1 = new Label(2, 2,
							supplier.getLinkman(), cellFormat);
					sheet.addCell(label_reason1);// 公司
					Label label_reason2 = new Label(2, 3,
							supplier.getLinkman(), cellFormat);
					sheet.addCell(label_reason2);// 名称(联系人)
					linkMan = supplier.getLinkman();
					Label label_reason3 = new Label(8, 4, supplier.getPhone(),
							cellFormat);
					sheet.addCell(label_reason3);// 供应商电话
				}
				// 发送人邮箱名称
				String userEmail = dictionaryService.getNameByCodeType(
						ConstantDict.FSRYXMC, ConstantDict.MAIL);
				// 邮箱发送人名称
				String username = dictionaryService.getNameByCodeType(
						ConstantDict.YXFSRMC, ConstantDict.MAIL);
				Label label_reason5 = new Label(2, 7,
						StringUtil.fixup(username), cellFormat);
				sheet.addCell(label_reason5);// 姓名Name

				Label label_reason6 = new Label(2, 10, userEmail, cellFormat);
				sheet.addCell(label_reason6);// 邮件Email
				Label label_reason7 = new Label(2, 11,
						StringUtil.fixup(DateUtil.date2string(new Date())),
						cellFormat);
				sheet.addCell(label_reason7);// 日期
				Label label_reason8 = new Label(0, 17, "至供应商质量联系人" + linkMan
						+ "", cellFormat);
				sheet.addCell(label_reason8);// 供应商联系人

				Label label_reason9 = new Label(
						0,
						18,
						"您的质量体系证书于"
								+ StringUtil.fixup(DateUtil
										.date2string(new Date())
										+ "过期Your quality certifications EXPIRED last"),
						cellFormat);
				sheet.addCell(label_reason9);// 过期日期
			}
			wbook.write();
			wbook.close();
			tBook.close();
			// 关闭文件输出流
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (StringUtil.isNotEmpty(errorMsg)) {
				throw new SystemException("生成EXCEL出错");
			}
		}
	}
	/**
	 * 只为页面导出,jsp展示内容
	 */
	public void txCreateJustExport(HttpServletRequest request, Long id,
			HttpServletResponse response){
		try {
			File tFile = new File(request.getSession().getServletContext()
					.getRealPath("/excelModel/")
					+ "/" + ConstantSqm.EXCEL_QUALITY_SYSTEM_EXCEL);// 创建模板文件对象
			File outFile = new File(request.getSession().getServletContext()
					.getRealPath("/excelModel/")
					+ "/" + ConstantSqm.EXCEL_QUALITY_SYSTEM_EXCEL_OUT);// 创建输出文件对象
			// 创建文件输出流对象
			FileOutputStream os = new FileOutputStream(outFile);
			// 模板工作簿对象
			Workbook tBook = Workbook.getWorkbook(tFile);
			// 输出工作簿对象
			WritableWorkbook wbook = Workbook.createWorkbook(os, tBook);
			WritableSheet sheet = wbook.getSheet(0);
			sheet.setName("环境体系");
			WritableCellFormat cellFormat = new WritableCellFormat();
			//cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN,jxl.format.Colour.ORANGE);
//			normalFormat.setBorder(Border.ALL, BorderLineStyle.THIN,
//				     jxl.format.Colour.GRAY_25);

			// 设置对齐方式
			cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.TOP);
			cellFormat.setAlignment(jxl.format.Alignment.LEFT);
			// 设置字体
			WritableFont bodyFont = new WritableFont(WritableFont.ARIAL, 12);
			cellFormat.setFont(bodyFont);
			// 第x列，第y行
			QualitySystem qualitySystem=qualitySystemService.get(id);
			if(qualitySystem!=null){
				Supplier supplier=supplierService.get(Long.parseLong(StringUtil.fixup(qualitySystem.getSupplierId())));
				Label label_reason1 = new Label(3, 5,
						supplier.getCode(), cellFormat);
				sheet.addCell(label_reason1);//供应商编号
				Label label_reason2 = new Label(3, 6,
						supplier.getName(), cellFormat);
				sheet.addCell(label_reason2);//供应商名称
				Label label_reason3 = new Label(9, 9,
						StringUtil.fixup(qualitySystem.getValue()), cellFormat);
				sheet.addCell(label_reason3);//得分
				Label label_reason4 = new Label(9, 11,
						StringUtil.fixup(DateUtil.date2string(qualitySystem.getCertificationDate())), cellFormat);
				sheet.addCell(label_reason4);//认证日期
				Label label_reason5 = new Label(9, 15,
						StringUtil.fixup(DateUtil.date2string(qualitySystem.getCertificationDate())), cellFormat);
				sheet.addCell(label_reason5);//过期日期
				Label label_reason6 = new Label(1, 18,
						qualitySystem.getComment(), cellFormat);
				sheet.addCell(label_reason6);//评论
				System.out.println(StringUtil.fixup(DateUtil.date2string(qualitySystem.getCertificationDate())));
			}
			wbook.write();
			wbook.close();
			tBook.close();
			os.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
	/**
	 * 下载生成后的EXCEL
	 */
	@Override
	public void txLoadJustExcel(HttpServletRequest request, Long id,
			HttpServletResponse response){
		txCreateJustExport(request, id, response);
		excelService.loadExcelModel(request, response,
				ConstantSqm.EXCEL_QUALITY_SYSTEM_EXCEL_OUT);
	}
}
